package com.guaoran.distributed.concurrent.program.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author : guaoran
 * @Description : <br/>
 * @date :2019/2/27 0:07
 */
public class RwLockDemo {
    static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = reentrantReadWriteLock.readLock();
    static Lock writeLock = reentrantReadWriteLock.writeLock();

    /**
     * 读写锁：适合读多写少
     *  读锁：共享锁
     *  写锁: 排它锁
     */

    //缓存
    static Map<String,Object> cacheMap = new HashMap<>();


    public Object get(String key){
        readLock.lock();
        try {
            return cacheMap.get(key);
        }finally {
            readLock.unlock();
        }
    }
    public Object set(String key,Object v){
        writeLock.lock();
        try {
            return cacheMap.put(key,v);
        }finally {
            writeLock.unlock();
        }
    }
}
